package com.eqdd.yiqidian.ui.gongneng.renshi.zuzhiguanli;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.InvitePersonToComFromContactActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.Person;
import com.eqdd.yiqidian.bean.rebuild.PhoneCombineBean;
import com.eqdd.yiqidian.bean.rebuild.PhoneStatusListResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.utils.ContactsUtil;
import com.eqdd.yiqidian.utils.PinYinUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.adapter.FloatingItemDecoration;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class InvitePersonToComFromContactActivity extends BaseActivity {
    private InvitePersonToComFromContactActivityCustom dataBinding;
    private StringBuilder stringBuilder;
    private ArrayList<PhoneCombineBean> phoneCombineBeanArrayList;
    private SlimAdapterEx<PhoneCombineBean> slimAdapterEx;
    private String departmentname;
    private String departmentId;
    private String careerName;
    private String careerId;
    private FloatingItemDecoration floatingItemDecoration;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_invite_person_to_com);
        initTopTitleBar(View.VISIBLE, "邀请加入");
        initTopRightText("邀请", v -> {
            String phones = getPhones();
            if (!TextUtils.isEmpty(phones)) {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.HR_INVITE)
                        .params("phones", phones)
                        .params("companyId", user.getCompanyId())
                        .params("company", user.getCompany())
                        .params("departId", departmentId)
                        .params("department", departmentname)
                        .params("postId", careerId)
                        .params("post", careerName)
                        .params("userGuid", user.getGuid())
                        .params("user", user.getUname())
                        .execute(new DialogCallBack<HttpResult>(this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    finish();
                                }
                            }
                        });
            } else {
                ToastUtil.showShort("请先选择至少一名人员");
            }
        });
    }

    private String getPhones() {
        StringBuilder stringBuilder = new StringBuilder();
        Flowable.fromIterable(slimAdapterEx.getData())
                .filter(phoneCombineBean -> phoneCombineBean.getCheck())
                .subscribe(phoneCombineBean -> stringBuilder.append(phoneCombineBean.getPhone() + ";"));
        if (TextUtils.isEmpty(stringBuilder.toString())) {
            return null;
        }
        return stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(";")).toString();
    }

    @Override
    public void initData() {
        departmentname = getIntent().getStringExtra(Config.DEPARTMENT_NAME);
        departmentId = getIntent().getStringExtra(Config.DEPARTMENT_ID);
        careerName = getIntent().getStringExtra(Config.CAREER_NAME);
        careerId = getIntent().getStringExtra(Config.CAREER_ID);


    }

    @Override
    public void setView() {
        dataBinding.waveSideBar.scroll(false);
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        floatingItemDecoration = new FloatingItemDecoration(this, Color.GRAY, 1, 1);
        floatingItemDecoration.backGroudColor(Color.GRAY)
                .textSize(30 * WindowUtil.csw / WindowUtil.width)
                .titleHeight(60 * WindowUtil.csw / WindowUtil.width);
        dataBinding.recyclerView.addItemDecoration(floatingItemDecoration);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_25, new SlimInjector<PhoneCombineBean>() {
            @Override
            public void onInject(PhoneCombineBean data, IViewInjector injector) {
                injector.text(R.id.tv_content, data.getPhoneName() + " " + data.getPhone())
                        .text(R.id.tv_right, data.getContent())
                        .checked(R.id.checkbox, data.getCheck())
                        .enable(R.id.checkbox, data.getEnable());
            }
        }).attachTo(dataBinding.recyclerView);
        dataBinding.waveSideBar.setRecyclerView(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (slimAdapterEx.getData().get(position).getEnable()) {
                        slimAdapterEx.getData().get(position).setCheck(!slimAdapterEx.getData().get(position).getCheck());
                        slimAdapterEx.notifyItemChanged(position);
                    }
                });
        dataBinding.floatingSearchView.setOnQueryChangeListener((oldQuery, newQuery) -> {
            if (TextUtils.isEmpty(newQuery)) {
                updateData(phoneCombineBeanArrayList);
//                slimAdapterEx.updateData(phoneCombineBeanArrayList);
//                dataBinding.waveSideBar.setData(phoneCombineBeanArrayList, phoneCombineBean -> PinYinUtil.getPinyin(phoneCombineBean.getPhoneName()).substring(0, 1), 0);
            } else {
                ArrayList<PhoneCombineBean> temp = new ArrayList<>();
                Flowable.fromIterable(InvitePersonToComFromContactActivity.this.phoneCombineBeanArrayList)
                        .filter(phoneCombineBean -> phoneCombineBean.getPhoneName().contains(newQuery) || phoneCombineBean.getPhone().contains(newQuery))
                        .subscribe(phoneCombineBean -> temp.add(phoneCombineBean), e -> {
                                },
                                () -> {
                                    updateData(temp);
//                                    slimAdapterEx.updateData(temp);
//                                    dataBinding.waveSideBar.setData(temp, phoneCombineBean -> PinYinUtil.getPinyin(phoneCombineBean.getPhoneName()).substring(0, 1), 0);
                                });
            }
        });
        ArrayList<Person> contacts = new ArrayList<>();
        phoneCombineBeanArrayList = new ArrayList<>();
        slimAdapterEx.updateData(phoneCombineBeanArrayList);
        stringBuilder = new StringBuilder();
        RxPermissions.getInstance(this).request(Manifest.permission.READ_CONTACTS)
                .subscribe(granted -> {
                    if (granted) {
                        showLoading();
                        System.out.println("读取联系人授权成功");
                        ArrayList<Person> quickAllContacts = ContactsUtil.getQuickAllContacts(this);
                        Collections.sort(quickAllContacts);

                        Flowable.fromIterable(quickAllContacts)//获取手机联系人，过滤相同手机号
                                .distinct(Person::getPhone)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(person -> {
                                    contacts.add(person);
                                    stringBuilder.append(person.getPhone() + ";");
                                }, e -> System.out.println(e.toString()), () -> {
                                    if (stringBuilder.lastIndexOf(";") < 0) {
                                        hideLoading();
                                        slimAdapterEx.updateData(new ArrayList<>());
                                        return;
                                    }
                                    stringBuilder = stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(";"));
                                    OkGo.<HttpResult<List<PhoneStatusListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.GET_PHONE_STATE)
                                            .params("phones", stringBuilder.toString())
                                            .params("companyId", user.getCompanyId())
                                            .execute(new JsonCallBack<HttpResult<List<PhoneStatusListResultBean>>>() {
                                                @Override
                                                public void onSuccess(Response<HttpResult<List<PhoneStatusListResultBean>>> response) {
                                                    HttpResult<List<PhoneStatusListResultBean>> httpResult = response.body();
                                                    if (httpResult.getStatus() == 200) {
                                                        Flowable.zip(Flowable.fromIterable(contacts), Flowable.fromIterable(httpResult.getItems()), new BiFunction<Person, PhoneStatusListResultBean, PhoneCombineBean>() {
                                                            @Override
                                                            public PhoneCombineBean apply(@NonNull Person person, @NonNull PhoneStatusListResultBean phoneStatusListResultBean) throws Exception {
                                                                if (person.getPhone().equals(phoneStatusListResultBean.getPhone())) {
                                                                    PhoneCombineBean phoneCombineBean = new PhoneCombineBean();
                                                                    phoneCombineBean.setPhone(person.getPhone());
                                                                    phoneCombineBean.setType(phoneStatusListResultBean.getStatus());
                                                                    phoneCombineBean.setContent(phoneStatusListResultBean.getMessage());
                                                                    phoneCombineBean.setPhoneName(person.getName());
                                                                    phoneCombineBean.setEnable(phoneStatusListResultBean.getStatus() != 2);
                                                                    phoneCombineBean.setCheck(false);
                                                                    return phoneCombineBean;
                                                                }
                                                                return null;
                                                            }
                                                        })
                                                                .subscribeOn(Schedulers.io())
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .subscribe(combine -> phoneCombineBeanArrayList.add(combine), e -> {
                                                                    hideLoading();
                                                                    System.out.println(e.toString());
                                                                }, () -> {
                                                                    updateData(phoneCombineBeanArrayList);
                                                                    hideLoading();
                                                                });
                                                    }
                                                }
                                            });
                                });
                    } else {
                        ToastUtil.showShort("如需邀请手机联系人入住公司，请在设置中打开通讯录权限");
                    }
                });


    }

    private void updateData(ArrayList<PhoneCombineBean> datas) {
        Map<Integer, String> keys = new HashMap<>();
        Flowable.fromIterable(datas)
                .distinct(phoneCombineBean -> PinYinUtil.head(phoneCombineBean.getPhoneName()))
                .subscribe(phoneCombineBean -> keys.put(datas.indexOf(phoneCombineBean), PinYinUtil.head(phoneCombineBean.getPhoneName()))
                        , e -> System.out.println(e.toString()), () -> {
                            floatingItemDecoration.setKeys(keys);
                        });
        slimAdapterEx.updateData(datas);
        dataBinding.waveSideBar.setData(datas, phoneCombineBean -> PinYinUtil.head(phoneCombineBean.getPhoneName()), 0);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {

        }
    }
}
